package dao.impl;

import dao.VipDao;
import domian.Vip;
import utils.BaseDAO;

import java.sql.*;
import java.util.Date;

public class VipDaoImpl implements VipDao {
    //添加vip
    @Override
    public Integer addVip(Vip vip) {
        String sql = "insert into vip(uid,vipStatus,openingTime,maturityTime) values(?,?,?,?)";
        Object[] arr = {vip.getUid(), vip.getVipStatus(), vip.getOpeningTime(), vip.getMaturityTime()};
        return BaseDAO.executeUpdate(sql, arr);
    }

    //修改vip
    @Override
    public Integer updateVip(Vip vip) {
        String sql = "update vip set vipStatus=? ,openingTime=? ,maturityTime=? where uid=?";
        Object[] arr = {vip.getVipStatus(), vip.getOpeningTime(), vip.getMaturityTime(), vip.getUid()};
        return BaseDAO.executeUpdate(sql, arr);
    }

    //查询单个vip
    @Override
    public Vip inquire(Integer uid) {
        Vip vip = null;
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try {
            //获取连接
            connection = BaseDAO.getConnection();
            //创建SQL语句
            String sql = "select * from vip where uid=?";
            //获取SQL语句对象
            ps = connection.prepareStatement(sql);
            ps.setInt(1, uid);
            //执行SQL语句
            resultSet = ps.executeQuery();
            if (resultSet.next()) {
                Integer id = resultSet.getInt("id");
                Integer vipStatus = resultSet.getInt("vipStatus");
                Date openingTime = new Date(resultSet.getTimestamp("openingTime").getTime());
                Timestamp mt = resultSet.getTimestamp("maturityTime");
                Date maturityTime = null;
                if (mt != null) {
                    maturityTime = new Date(mt.getTime());
                }
                vip = new Vip(id, uid, vipStatus, openingTime, maturityTime);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            BaseDAO.close(connection, ps, resultSet);
        }
        return vip;
    }
}
